package com.winbomb.kingcard.base;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import android.util.Log;

import com.winbomb.kingcard.IForce;
import com.winbomb.kingcard.IPlayer;

public class Force implements IForce {

	public static final int RT_ALEIN = 0; // 同盟关系

	/** 势力的主公 */
	private IPlayer master;

	/** 势力的成员(包括主公) */
	private Set<IPlayer> memberSet;

	/** 势力的同盟势力 */
	private Set<IForce> aleinSet;

	private int aleinFlag;

	public Force(IPlayer player) {
		this.master = player;
		this.memberSet = new HashSet<IPlayer>();
		this.memberSet.add(master);
		this.aleinSet = new HashSet<IForce>();
		this.aleinFlag = -1;
	}

	@Override
	public void addMember(IPlayer member) {
		memberSet.add(member);
	}

	@Override
	public int getCardCount() {
		int count = 0;
		for (IPlayer member : memberSet) {
			count += member.getCardCount();
		}

		return count;
	}

	@Override
	public IPlayer getMaster() {
		return master;
	}

	@Override
	public IPlayer[] getMembers() {
		return memberSet.toArray(new IPlayer[memberSet.size()]);
	}

	@Override
	public int getMemeberCount() {
		return memberSet.size();
	}

	@Override
	public void removeMember(IPlayer member) {
		if (member == master) {
			master = null;
		}

		memberSet.remove(member);
		update();
	}

	@Override
	public void update() {

		if (this.master != null) {
			return;
		}

		// 把所有灭亡的势力设为null,并从member中除去
		Iterator<IPlayer> it = memberSet.iterator();
		while (it.hasNext()) {
			IPlayer member = it.next();
			if (!member.isAlive()) {
				member.clearForce();
				it.remove();
			}
		}

		IPlayer newMaster = null;
		for (IPlayer member : memberSet) {
			if (newMaster == null || member.getCardCount() > newMaster.getCardCount()) {
				newMaster = member;
			}
		}
		this.master = newMaster;
	}

	@Override
	public int getForceFlag() {
		return this.master.getPlayerIndex();
	}

	@Override
	public void clearRelations() {
		this.aleinSet.clear();
	}

	@Override
	public boolean hasRelation(IForce force, int relation) {
		return (force == this || this.aleinSet.contains(force));
	}

	@Override
	public void setRelation(IForce force, int relation) {
		this.aleinSet.add(force);

	}

	@Override
	public int getAleinFlag() {
		return this.aleinFlag;
	}

	@Override
	public void setAleinFlag(int flag) {
		this.aleinFlag = flag;
	}

	@Override
	public void changeMaster(IPlayer master) {

		// 先检查新的master是否在memberSet之中
		if (!memberSet.contains(master)) {
			Log.w("Force", "Change Master Failed, cause new master is not in member set.");
			return;
		}

		this.master = master;
	}
}
